# Maestro is a music database search utility
# Copyright (C) 2010 Robert Mens
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

from __future__ import print_function
import os, mutagen, os.path
import settings

def get_info_from_filename(music_library, filename):
    pass
    #format: artist/album/tracknr - songtitle.ext

    #first we have to cut off the music_library base from the filename
    
def scan_for_missing_files():
    mdb = settings.mdb
    removed_files = []
    files = mdb.get_files()
    for filename in files:
        if not os.path.exists(filename):
            mdb.remove_song(filename)
            removed_files.append(filename)

    return removed_files

def scan_library(music_library, db):

    #get absolute path first
    music_library = os.path.abspath(os.path.expanduser(music_library))
    #database = os.path.abspath(os.path.expanduser(database))

    print("Scanning folder %s\n" % music_library)

    filelist = []
    filetype_counter = dict()
    file_counter = 0
    
    for files in os.walk(music_library):
      if files[2]:
        for filename in files[2]:
          filelist.append(os.path.join(files[0], filename))

    supported_filetypes = ['mp3','flac','ogg','m4a','mpc','wma', 'aac', 'mp4']

    tmp_filelist = []
    tmp_filelist.extend(filelist)

    if filelist:
        for filename in filelist:
            extension = os.path.splitext(filename)[1].lower()[1:]
            if not extension in supported_filetypes:
                tmp_filelist.remove(filename)
                #print("%s not supported" %(extension))
            else:
                #check whether or not it's already in our database
                if not extension in filetype_counter: filetype_counter[extension] = 0
                filetype_counter[extension] += 1
                if db.file_exists_in_database(filename):
                    tmp_filelist.remove(filename)
                                    
    filelist = tmp_filelist                

       
    print("Supported files found:\n")
    for filetype in filetype_counter.keys():
        file_counter += filetype_counter[filetype]
        print("%s: %s"%(filetype, str(filetype_counter[filetype])))

    print("\nTotalling %s files" % (str(file_counter)))

    file_counter = 0


    print ("New files: "+ str(len(filelist)))

    
    print("Scanning files for tags...\n")

    exceptionlist = []

    for filename in filelist:
        try:
            info = mutagen.File(filename, None, True)
        except Exception as e:
            e.music_filename = filename
            exceptionlist.append(e)
            if db.add_song(filename) == True: file_counter += 1
            continue
        
        if not info:
            #No tag found, however since its a valid file just add it to the db
            if db.add_song(filename) == True: file_counter += 1
            continue

        try:
            title = info["title"][0]
        except(KeyError):
            title = ""

        try:
            artist= info["artist"][0]
        except(KeyError):
            artist = ""

        try:
            album = info["album"][0]
        except(KeyError):
            album = ""

        try:
            tracknumber = info["tracknumber"][0]
        except(KeyError):
            tracknumber = ""

        
        if db.add_song(filename, title, artist, album, tracknumber) == True: file_counter += 1
        

    print("Added "+str(file_counter)+" files.")
    #db.close()

    if exceptionlist:
        for ex in exceptionlist:
            print("Exception caused by file: " + ex.music_filename +"\n"+str(ex))

if __name__ == "__main__":
    print("MusicMeister\n")

    #scan_library(u"tests/")
    db = MusicDB(u'test2.db')
    #db.create_new_db()
    scan_library(u"/home/robert/Music/",db)
   

